//
//  AsyncImageView.m
//  Postcard
//
//  Created by markj on 2/18/09.
//  Copyright 2009 Mark Johnson. You have permission to copy parts of this code into your own projects for any use.
//  www.markj.net
//

#import "pblasyncimageview.h"
#import "ASIHTTPRequest.h"
#import <QuartzCore/QuartzCore.h>
#import "BusinessOperation.h"
@implementation PBLAsyncImageView
@synthesize _imageRequestURL;
@synthesize _numStateRequested;
@synthesize m_BoolSetImage;
@synthesize m_ImageBuffer;
@synthesize m_FloderName;
@synthesize m_PngName;
static NSOperationQueue*  _OperationQue;

-(id)initWithFrame:(CGRect)frame{
	if ((self =[super initWithFrame:frame])) {
		m_BoolSetImage = NO;
//        p_ActLoadView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//        p_ActLoadView.frame = CGRectMake((frame.size.width-16)/2, (frame.size.height-16)/2, 16, 16);
//        [self addSubview:p_ActLoadView];
        if(_OperationQue == nil){
            _OperationQue = [[NSOperationQueue alloc] init];
            [_OperationQue setMaxConcurrentOperationCount:2];
        }
	}
	return self;
}

- (void)loadImageFromURL{
    NSURL* tRequestURL =nil;
    if ([_imageRequestURL isKindOfClass:[NSString class]]) {
        tRequestURL =[NSURL URLWithString:_imageRequestURL];
    }else{
        tRequestURL =_imageRequestURL;
    }
	_imageASIHttpRequest = [ASIHTTPRequest requestWithURL:tRequestURL];
    [_imageASIHttpRequest setTimeOutSeconds:20.f];
	[_imageASIHttpRequest setDelegate:self];
	[_imageASIHttpRequest setDidFinishSelector:@selector(okimg:)];
	[_imageASIHttpRequest setDidFailSelector:@selector(failimg:)];
	_numStateRequested = haveSend_Request;
    [_imageASIHttpRequest startAsynchronous];
    [_imageASIHttpRequest retain];
}

- (void)customLoadImageFromURL{
//    [p_ActLoadView performSelectorOnMainThread:@selector(startAnimating) withObject:nil waitUntilDone:NO];
    [self loadImageFromURL];
}

//- (void)asyReadFileImg{
//    if (_showImageView.image == nil && _numStateRequested == suc_Request) {
//        _numStateRequested = file_reading;
//        NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:self,@"object",nil];
//        BusinessOperation *businessOperation = [[BusinessOperation alloc] init];
//        businessOperation.target = self;
//        businessOperation.object = dictionary;
//        businessOperation.selector = @selector(asyReadFileImg:);
//        [_OperationQue addOperation:businessOperation];
//        [businessOperation release];
//    }
//}
//
//-(void) asyReadFileImg:(NSDictionary *)dictionary
//{
//    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//    //PBLAsyncImageView* tAsyImg = [dictionary objectForKey:@"object"];
//    
//    NSString* tTemp = NSTemporaryDirectory();
//    
//    NSString *pblName=[tTemp stringByAppendingPathComponent:m_FloderName];
//
//    NSString *FileName=[pblName stringByAppendingPathComponent:m_PngName];
//    UIImage* tImg = [UIImage imageWithContentsOfFile:FileName];
//    [_showImageView performSelectorOnMainThread:@selector(setImage:) withObject:tImg waitUntilDone:YES];
//    _numStateRequested = suc_Request;
//
//    
//    [pool drain];
//}


-(void)setAsyImg:(NSDictionary *)dictionary
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSMutableData* tMData =[dictionary objectForKey:@"img"];
    PBLAsyncImageView* tAsyImg = [dictionary objectForKey:@"object"];
    tAsyImg.m_ImageBuffer =  [UIImage imageWithData:tMData];
	[tAsyImg.m_ImageBuffer retain];
    
	
    
	if (m_BoolSetImage) {
        
		[tAsyImg initSelfImgView:tAsyImg.m_ImageBuffer asyImg:tAsyImg];
	}
    _numStateRequested = suc_Request;
    [pool drain];
}

-(void)okimg:(ASIHTTPRequest*) request{
	//NSMutableData* imgdata = (NSMutableData*)[request responseData];
	if (m_ImageBuffer != nil) {
		[m_ImageBuffer release];
		m_ImageBuffer=nil;
	}
    
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:[request responseData],@"img",self,@"object",nil];
    BusinessOperation *businessOperation = [[BusinessOperation alloc] init];
    businessOperation.target = self;
    businessOperation.object = dictionary;
    businessOperation.selector = @selector(setAsyImg:);
    [_OperationQue addOperation:businessOperation];
    [businessOperation release];

    
    [_imageASIHttpRequest release];
    _imageASIHttpRequest = nil;
}

-(void) initSelfImgView :(UIImage*)img asyImg:(PBLAsyncImageView*)f_object{
	if (_showImageView != nil) {
		[_showImageView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:YES];
		[_showImageView release];
		_showImageView = nil;
	}
	if (m_ImageBuffer != nil && _numStateRequested == suc_Request) {
		_showImageView = [[UIImageView alloc] initWithImage:m_ImageBuffer];
		[m_ImageBuffer release];
		m_ImageBuffer = nil;
		_numStateRequested = done_Image;
	}else {
		_showImageView = [[UIImageView alloc] initWithImage:img];
	}
    
    NSString* tTemp = NSTemporaryDirectory();
    NSString *pblName=[tTemp stringByAppendingPathComponent:m_FloderName];
    NSFileManager* tFileManager = [NSFileManager defaultManager];
    NSError* tError = nil;
    if (![tFileManager fileExistsAtPath:pblName]) {
        [tFileManager createDirectoryAtPath:pblName withIntermediateDirectories:NO attributes:nil error:&tError];
    }
    NSString *FileName=[pblName stringByAppendingPathComponent:m_PngName];
    if ([tFileManager fileExistsAtPath:FileName]) {
        [tFileManager removeItemAtPath:FileName error:&tError];
    }
    [self writeImage:img toFileAtPath:FileName];


	CGRect aframe = self.bounds;
	_showImageView.frame =aframe;
	self.contentMode = UIViewContentModeScaleAspectFit;
	[f_object performSelectorOnMainThread:@selector(addSubview:) withObject:_showImageView waitUntilDone:YES];
    UIView* tInBG = (UIView*)[f_object viewWithTag:0x34];
    
    [self performSelectorOnMainThread:@selector(fuckyoushow:) withObject:tInBG waitUntilDone:YES];
    
    [f_object performSelectorOnMainThread:@selector(bringSubviewToFront:) withObject:tInBG waitUntilDone:YES];
    
    UILabel* tInLab = (UILabel*)[f_object viewWithTag:0x33];

    [self performSelectorOnMainThread:@selector(fuckyoushow:) withObject:tInLab waitUntilDone:YES];
    [f_object performSelectorOnMainThread:@selector(bringSubviewToFront:) withObject:tInLab waitUntilDone:YES];
    
}

-(void)fuckyoushow:(UIView*)f_sender
{
    f_sender.hidden =NO;
}


-(void)failimg:(ASIHTTPRequest*) request{
	//获取图片失败
	NSLog(@"http jpeg error");
	_numStateRequested = fail_Request;
//    [p_ActLoadView stopAnimating];
//    [p_ActLoadView removeFromSuperview];
//    [p_ActLoadView release];
//    p_ActLoadView =nil;
    
    [_imageASIHttpRequest release];
    _imageASIHttpRequest = nil;
}

-(UIImage*) GetUIImage{
	for (id object in [self subviews]) {
		if ([object isKindOfClass:[UIImageView class]]) {
			return ((UIImageView*)object).image;
		}
	}
	return nil;
}

-(void) SetUIImage :(UIImage*)img{
	BOOL found = NO;
	for (id object in [self subviews]) {
		if ([object isKindOfClass:[UIImageView class]]) {
			((UIImageView*)object).image = img;
			found = YES;
		}
	}
	if (!found) {
        _showImageView = [[UIImageView alloc] initWithImage:img];
        CGRect aframe = self.bounds;
        _showImageView.frame =aframe;
        [self addSubview:_showImageView];
		_numStateRequested = done_Image;
	}
}

-(UIImage*) GetBufferImage{
	return m_ImageBuffer;
}

-(UIImageView*) getInImageView
{
    return _showImageView;
}

- (void)dealloc {
    if (_imageASIHttpRequest != nil && _numStateRequested == haveSend_Request) {
		[_imageASIHttpRequest setDelegate:nil];
		[_imageASIHttpRequest setDidFinishSelector:nil];
		[_imageASIHttpRequest setDidFailSelector:nil];
		[_imageASIHttpRequest cancel];
    }
    [_imageASIHttpRequest release];
    _imageASIHttpRequest = nil;
	if (_showImageView != nil) {
		[_showImageView removeFromSuperview];
		[_showImageView release];
	}
	if (m_ImageBuffer != nil) {
		[m_ImageBuffer release];
		m_ImageBuffer = nil;
	}
//    [p_ActLoadView removeFromSuperview];
//    [p_ActLoadView release];
//    p_ActLoadView =nil;
    [_imageRequestURL release];
    [super dealloc];
}


- (BOOL)writeImage:(UIImage*)image toFileAtPath:(NSString*)aPath

{
    
    if ((image == nil) || (aPath == nil) || ([aPath isEqualToString:@""]))
        
        return NO;
    
    
    
    @try
    
    {
        
        NSData *imageData = nil;
        
        NSString *ext = [aPath pathExtension];
        
        if ([ext isEqualToString:@"png"])
            
        {
            imageData = UIImagePNGRepresentation(image);
            
        }
        else
            
        {
            
            // the rest, we write to jpeg
            
            // 0. best, 1. lost. about compress.
            
            imageData = UIImageJPEGRepresentation(image, 0);
            
        }
        
        
        
        if ((imageData == nil) || ([imageData length] <= 0))
            
            return NO;
        
        
        
        [imageData writeToFile:aPath atomically:YES];
        
        return YES;
        
    }
    
    @catch (NSException *e)
    
    {
        
        NSLog(@"create thumbnail exception.");
        
    }
    
    
    
    return NO;
    
}


@end
